/**
 * 通过绑定元素调整某个元素的宽度
 * @param {*} el 绑定dom
 * @param {*} binding 绑定对象传的值(传元素选择器，否则不生效)
 */
const adjustWidth = {
  inserted: (el, binding) => {
    let mousePositionStartX
    let mousePositionEndX

    let dom
    const v = binding.value
    if (typeof v === 'string') {
      dom = document.querySelector(v)
    }
    if (!dom) return

    const moving = (event) => {
    // 防止文字选中
      window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty()
      event = event || window.event
      mousePositionEndX = event.clientX
      let width = dom.offsetWidth
      width = width + mousePositionEndX - mousePositionStartX
      mousePositionStartX = mousePositionEndX
      dom.style.width = width + 'px'
    }

    const endMove = (event) => {
      window.removeEventListener('mousemove', moving)
      window.removeEventListener('mouseup', endMove)
    }

    el.onmousedown = (event) => {
      endMove()
      event = event || window.event
      window.addEventListener('mousemove', moving)
      window.addEventListener('mouseup', endMove)
      mousePositionStartX = event.clientX
    }
  }
}

export default adjustWidth
